from django.shortcuts import render
from django.views import View
from rest_framework.decorators import action
from rest_framework.viewsets import ViewSet, ModelViewSet
from rest_framework.response import Response
from rest_framework.permissions import IsAdminUser,IsAuthenticated

from meidu_express.models import ExpressInfo
from meiduo_express.kdbird_express.kdniao_express import *
from meiduo_express.kdbird_express.api_settings import *
from meiduo_express.kdbird_express.request_type import *
from meiduo_express.kdbird_express.request_urls import *
from users.models import User
from orders.models import OrderInfo
from meiduo_mail.utils.views import LoginRequiredView
from meiduo_mail.apps.meidu_express.serializers import *
from meiduo_express.meiduo_express import MeiduoExpress
from .tasks import meiduo_place_order



# Create your views here.


# class MeiduoExpress(KDNiaoExpress,View):
#
#     def get(self,request_data):
#         self.RequestType = PLACE_ORDER_URL
#         return self.send_request(request_data)
class MeiduoExpressView(ViewSet,LoginRequiredView):
    #
    # def get_permissions(self):
    #     if self.action == "place_order" or self.action == "userinfo":
    #         return [IsAdminUser()]
    #     elif self.action == "prompt_check":
    #         return [IsAuthenticated()]

    @action(methon=['get'],detail=False)
    def userinfo(self,request, pk):
        Sender = request.user
        Reveiver = User.objects.get(orderinfo__order_id=pk)
        return Response({

            'Sender':{
                'Name':Sender.username,
                'Mobile':Sender.mobile,
                'ProvinceName': Sender.default_address.province.name,
                'CityName': Sender.default_address.city.name,
                'ExpAreaName': Sender.default_address.district.name,
                'Address':Sender.default_address.place
            },
            'Receiver':{
                'Name': Reveiver.username,
                'Mobile': Reveiver.mobile,
                'ProvinceName': Reveiver.default_address.province.name,
                'CityName': Reveiver.default_address.city.name,
                'ExpAreaName': Reveiver.default_address.district.name,
                'Address': Reveiver.default_address.place
            }
        })

    @action(method=['post'],detail=False)
    def palce_order(self,request):
        commodity_str = request.data.get('Commodity')
        commodity_list = commodity_str.split(',')
        commodity = []
        for i in commodity_list :
            commodity.append({'GoodsName':i})

        request.data['Commodity'] =  commodity

        print(request.data['Commodity'])
        print(request.data)

        s = PlaceOrderSerializer(data=request.data)
        s.is_valid(raise_exception=True)



        EX = MeiduoExpress()
        res = EX.place_order(s.validated_data)
        # meiduo_place_order.delay(s.validated_data, staff_id=request.user.id)
        if res['Success']:
            ExpressInfo.objects.create(
                order_id=res['Order']['OrderCode'],
                staff_id=request.user.id,
                logistic_code=res['Order']['LogisticCode'],
                shipper_code=res['Order']['ShipperCode']
            )

            return Response({"result": True})
        return Response({"result": False})

#
class Meiduo_search(ModelViewSet):
    # def get_permissions(self):
    #     """
    #     重写该函数实现:
    #     1、下单接口必须是超级管理员调用
    #     2、查询接口只需经过身份认证即可
    #     """
    #     if self.action == "place_order":
    #         return [IsAdminUser()]
    #     elif self.action == "prompt_check":
    #         return [IsAuthenticated()]

    def get(self,request,pk):
        ex_info = ExpressInfo.objects.get(order_id=pk)
        EX = MeiduoExpress()
        res = EX.prompt_check(request_data={
            'OrderCode':ex_info.order_id,
            'ShipperCode':ex_info.shipper_code,
            'LogisticCode':ex_info.logistic_code
        })
        print(res)
        print(res['Traces'])
        return Response({'Traces': res['Traces']})
        # expinfo = ExpressInfo.objects.get(order_id=pk)
        # mp = MeiduoExpress()
        # res = mp.prompt_check(request_data={
        #     "OrderCode": expinfo.order_id,
        #     "ShipperCode": expinfo.shipper_code,
        #     "LogisticCode": expinfo.logistic_code,
        # })
        # return Response(res)











